package com.bojiu.lawsearch.lawsearch.controller;

import com.bojiu.lawsearch.lawsearch.model.*;
import com.bojiu.lawsearch.lawsearch.service.TaskService;
import com.bojiu.lawsearch.lawsearch.service.WechatUserService;
import com.bojiu.lawsearch.lawsearch.service.WxGoodsService;
import com.bojiu.lawsearch.lawsearch.util.AuthorizationHandle;
import com.bojiu.lawsearch.lawsearch.util.JsonResult;
import com.bojiu.lawsearch.lawsearch.util.ResultCode;
import com.bojiu.lawsearch.lawsearch.util.UtilTools;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * @author: afdiao
 * @Date：2020/3/2 21:35
 * @Description:
 */
@Api(description = "应用端相关接口")
@RestController
@RequestMapping("wechatuser")
@Slf4j
public class WechatUserController {

    @Autowired
    WechatUserService wechatUserService;

    @Autowired
    AuthorizationHandle authorizationHandle;

    @Autowired
    WxGoodsService wxGoodsService;

    @Autowired
    TaskService taskService;

    /**
     * 获取基本信息
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "获取当前用户信息", notes = "获取用户 信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = WechatUser.class),
            @ApiResponse(code = 600, message = "未检测到登录，跳转重新登录"),
    })
    @GetMapping("baseinfo")
    public JsonResult getBaseInfo(HttpServletRequest request) {
        log.debug("start to get userInfo================================");
        //判断用户权限
        JsonResult jsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(jsonResult.getCode())) {
            log.error("审核没有通过");
            return jsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(jsonResult.getData()));
        WechatUser wechatUser = wechatUserService.getByUserId(userId, request.getHeader("sign"));
        log.debug("用户信息：{}", wechatUser);
        return new JsonResult(ResultCode.SUCCESS, wechatUser);
    }

    /**
     * 获取会员商品价格
     *
     * @return
     */
    @ApiOperation(value = "获取微信充值会员消息", notes = "微信充值会员消息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = WxGoods.class),
    })
    @GetMapping("memberGoods")
    public JsonResult getMemberGoods() {
        List<WxGoods> goodsList = wxGoodsService.getGoodsList(1);
        return new JsonResult(ResultCode.SUCCESS, goodsList);
    }


    /**
     * 更新密码
     *
     * @param string
     * @param request
     * @return
     */
    @ApiOperation(value = "更新密码", notes = "更新密码，说明：newPassword  新密码；    oldPassword 旧密码； ")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = WxGoods.class),
            @ApiResponse(code = 600, message = "未登录"),
    })
    @PostMapping("updatePassword")
    public JsonResult updatePassword(@RequestBody String string, HttpServletRequest request) {
        //判断用户权限
        JsonResult jsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(jsonResult.getCode())) {
            log.error("审核没有通过");
            return jsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(jsonResult.getData()));
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(string, JsonObject.class);
        String newPassword = jsonObject.get("newPassword").getAsString();
        String oldPassword = jsonObject.get("oldPassword").getAsString();
        JsonResult result = wechatUserService.updatePassword(newPassword, oldPassword, userId);
        return result;
    }

    /**
     * 更新基本资料
     *
     * @param request
     * @param string
     * @return
     */
    @ApiOperation(value = "修改基本信息", notes = "注：需要提交信息：headImg 头像,上传后返回的文件名；nickName 昵称； sex 性别； province  省份；  city 市  ")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 100, message = "失败"),
            @ApiResponse(code = 600, message = "未登录"),
    })
    @PostMapping("updateBaseInfo")
    public JsonResult updateBaseInfo(HttpServletRequest request, @RequestBody String string) {
        //判断用户权限
        JsonResult jsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(jsonResult.getCode())) {
            log.error("审核没有通过");
            return jsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(jsonResult.getData()));
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(string, JsonObject.class);
        try {
            String headImg = jsonObject.get("headImg").getAsString();
            String nickName = jsonObject.get("nickName").getAsString();
            int sex = jsonObject.get("sex").getAsInt();
            String province = jsonObject.get("province").getAsString();
            String city = jsonObject.get("city").getAsString();
            wechatUserService.updateBaseInfo(headImg, nickName, sex, province, city, userId);
            return new JsonResult(ResultCode.SUCCESS);
        } catch (Exception e) {
            log.error("error to update baseInfo,error is :{}", e);
            return new JsonResult(ResultCode.FAIL);
        }
    }

    /**
     * 工程师申请
     *
     * @param engineer
     * @param request
     * @param errors
     * @return
     */
    @ApiOperation(value = "申请工程师", notes = "注：需要提交信息：headImg 头像,上传后返回的文件名；nickName 昵称； sex 性别； province  省份；  city 市  ")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 100, message = "失败"),
            @ApiResponse(code = 600, message = "未登录"),
            @ApiResponse(code = 1600, message = "邮箱已被使用"),
    })
    @PostMapping("engineer/register")
    public JsonResult engineerReg(@ApiParam(name = "申请明细", value = "json格式", required = true) @Valid @RequestBody Engineer engineer, HttpServletRequest request, Errors errors) {
        //判断用户权限
        JsonResult checkjsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(checkjsonResult.getCode())) {
            log.error("审核没有通过");
            return checkjsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(checkjsonResult.getData()));
        if (errors.hasErrors()) {
            JsonResult jsonResult = UtilTools.handleNullField(errors);
            return jsonResult;
        }
        JsonResult jsonResult = wechatUserService.registerEngineer(userId, engineer);
        return jsonResult;
    }

    /**
     * 我的收藏
     *
     * @param string
     * @param request
     * @return
     */
    @ApiOperation(value = "我的收藏", notes = "提供查询条件：text   ")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 100, message = "失败"),
            @ApiResponse(code = 600, message = "未登录"),
    })
    @PostMapping("mycollect")
    public JsonResult myCollect(@ApiParam(name = "查询条件text", value = "json格式", required = true)@RequestBody String string, HttpServletRequest request) {
        //判断用户权限
        JsonResult checkjsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(checkjsonResult.getCode())) {
            log.error("审核没有通过");
            return checkjsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(checkjsonResult.getData()));
        JsonObject jsonObject = new Gson().fromJson(string, JsonObject.class);
        String text = jsonObject.has("text") ? jsonObject.get("text").getAsString() : null;
        JsonResult jsonResult = wechatUserService.myCollect(userId, text);
        return jsonResult;
    }

    @ApiOperation(value = "充值余额", notes = "用户充值余额")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = JsonResult.class),
            @ApiResponse(code = 100, message = "失败"),
            @ApiResponse(code = 600, message = "未登录"),
    })
    @GetMapping("fee/{num}")
    public JsonResult fee(@ApiParam(name = "fee  充值的金额，单位为元", value = "金额", required = true)@PathVariable("num") int num,HttpServletRequest request) {
        //判断用户权限
        JsonResult checkjsonResult = authorizationHandle.webHandler(request);
        if (!"200".equals(checkjsonResult.getCode())) {
            log.error("审核没有通过");
            return checkjsonResult;
        }
        int userId = Integer.parseInt(String.valueOf(checkjsonResult.getData()));
        JsonResult result = taskService.fee(num, userId, request);
        return result;
    }
}
